import React, { Component } from 'react'
import { InputItem, Tabs, Toast } from 'antd-mobile';
import axios from '../utils/http'
import '../assets/style/mapNav.less'
const { BMap,
    BMAP_ANCHOR_TOP_LEFT,//控件将定位到地图的左上角
    BMAP_ANCHOR_TOP_RIGHT,//控件将定位到地图的右上角
    BMAP_DRIVING_POLICY_FIRST_HIGHWAYS,//优先高速
    BMAP_DRIVING_POLICY_AVOID_CONGESTION,//避开拥堵
    BMAP_TRANSIT_POLICY_LEAST_TRANSFER,//最少换乘
    BMAP_TRANSIT_POLICY_LEAST_TIME,//最少时间
    BMAP_TRANSIT_TYPE_POLICY_AIRPLANE//飞机优先
} = window;
export default class MapNav extends Component {
    constructor(props) {
        super(props)
        const address = this.props.location.state
        this.state = {
            start: '',
            end: '',
            city: '',
            title: '驾车',
            condition: '最少时间',
            startPoint: {},
            endPoint: {},
            address: address,
            closestatus: true,
            msg: '展开',
            store: []
        }
        console.log(this.props.location.state, 123456);
    }
    componentDidMount() {
        this.request()
        this.showMap()
    }

    request = async () => {
        const resdata = await axios({
            url: '/getNew/house',
            method: 'post',
        })
        console.log(resdata.data);
        if (resdata.data.code === "200") {
            let resArray = JSON.parse(JSON.stringify(this.state.store))
            resdata.data.data.forEach(item => {
                if (this.state.address !== item.address) {
                    resArray.push(item.address)
                }
            })
            this.setState({
                store: resArray
            })
        } else {
            Toast.fail(resdata.data.msg);
        }
    }

    showMap = () => {
        // 创建Map实例
        this.map = new BMap.Map("allmap");
        //加载控件
        this.control()
        this.localSearch = new BMap.LocalSearch(this.map);
        var myGeo = new BMap.Geocoder();
        myGeo.getPoint(this.state.address, (startPoint) => {
            if (startPoint) {
                this.map.centerAndZoom(startPoint, 10);
                //自定义图片控件
                var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(22, 26), {
                    offset: new BMap.Size(10, 25), // 指定定位位置
                    imageOffset: new BMap.Size(0, 0 - 10 * 25) // 设置图片偏移
                });
                //标注提示控件
                const label = new BMap.Label('目标地', {
                    offset: new BMap.Size(30 - 5)
                });
                label.setStyle({
                    background: '#2957d6',
                    border: '1px solid "#ff8355"',
                    borderRadius: "5px",
                    color: '#fff',
                    height: "15px",
                    lineHeight: "15px",
                    textAlign: "center",
                    width: "60px",
                    top: '50px'
                })
                var marker = new BMap.Marker(startPoint, { icon: myIcon });
                marker.setLabel(label);
                this.map.addOverlay(marker);
                var myGeo = new BMap.Geocoder();
                let array = this.state.store
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];
                    myGeo.getPoint(element, (point) => {
                        //附近房源的标记控件
                        var marker = new BMap.Marker(point);
                        const label = new BMap.Label('距离该地' + (this.map.getDistance(startPoint, point)).toFixed(2) + '米', {
                            offset: new BMap.Size(30 - 5)
                        });
                        label.setStyle({
                            background: '#ff8355',
                            border: '1px solid "#ff8355"',
                            borderRadius: "5px",
                            color: '#fff',
                            height: "15px",
                            lineHeight: "15px",
                            textAlign: "center",
                            width: "160px",
                            top: '50px'
                        })
                        marker.setLabel(label);
                        this.map.addOverlay(marker);
                    })
                }
            }
        })
    }

    control = () => {
        // 将城市定位控件添加到地图上
        this.map.addControl(new BMap.CityListControl({
            // 城市定位控件的停靠位置（可选，默认左上角）
            anchor: BMAP_ANCHOR_TOP_LEFT,
            // 城市定位控件基于停靠位置的偏移量（可选）
            offset: new BMap.Size(10, 5)
        }));
        //缩放控件
        this.map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_RIGHT, offset: new BMap.Size(10, 10) }));
        //比例尺控件
        this.map.addControl(new BMap.ScaleControl());
        //输入框提示控件
        var ac1 = new BMap.Autocomplete({ input: "start", location: this.map });
        var ac2 = new BMap.Autocomplete({ input: "end", location: this.map });
        ac1.addEventListener("onconfirm", this.handleConform1);
        ac2.addEventListener("onconfirm", this.handleConform2);
    }


    getData = (e) => {
        let _value = e.item.value;
        console.log(e, 123);
        let myValue =
            _value.province +
            _value.district +
            _value.street +
            _value.business;
        this.setState({
            city: _value.city
        })

        return myValue
    }

    handleConform1 = e => {
        const myValue = this.getData(e)
        this.GetAddress(myValue, 'start')
        if (myValue && this.state.end) {
            console.log(myValue);
            this.TravelPlan()
        }
    };

    handleConform2 = e => {
        const myValue = this.getData(e)
        this.GetAddress(myValue, 'end')
        if (!this.state.start) {
            Toast.fail('请输入起始位置')
            return
        } else {
            console.log(this.state.startPoint, '149');
            setTimeout(() => {
                this.TravelPlan()
            }, 100)
        }

    }

    GetAddress(myValue, Address) {
        this.myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上，并调整地图视野
        this.myGeo.getPoint(myValue, (point) => {
            console.log(point, '当前坐标');
            if (point) {
                if (Address === 'start') {
                    this.setState({
                        start: myValue,
                        startPoint: point
                    })
                } else {
                    this.setState({
                        end: myValue,
                        endPoint: point
                    })

                }
            } else {
                Toast.fail('抱歉，位置未找到')
            }
        }, this.state.city)
    }

    //根据坐标查询驾车路线查询
    drive = (value) => {
        //清除原在地图的标记
        this.map.clearOverlays();
        console.log(this.state.endPoint, '结束坐标');
        if (this.state.startPoint.lng && this.state.endPoint.lng) {
            console.log(1111);
            var start = new BMap.Point(this.state.startPoint.lng, this.state.startPoint.lat);
            var end = new BMap.Point(this.state.endPoint.lng, this.state.endPoint.lat);
            this.driving = new BMap.DrivingRoute(this.map, {
                renderOptions: { map: this.map, panel: "r-result", autoViewport: true },
            });
            //根据坐标查询
            this.driving.setPolicy(value)
            this.driving.search(start, end);
            document.getElementById('MapList').style.display = 'none'
        } else {
            console.log('没坐标');
        }
    }

    //根据位置查询步行路线查询
    walk(value) {
        //清除原在地图的标记
        this.map.clearOverlays();
        if (this.state.start && this.state.end) {
            this.walking = new BMap.WalkingRoute(this.map, { renderOptions: { map: this.map, panel: "r-result", autoViewport: true } });
            this.walking.getResults(value)
            this.walking.search(this.state.start, this.state.end);
        }
        document.getElementById('MapList').style.display = 'block'
    }

    //根据坐标查询公交路线查询
    transit(value) {
        //清除原在地图的标记
        this.map.clearOverlays();
        if (this.state.startPoint.Ye && this.state.endPoint.Ye) {
            this.transits = new BMap.TransitRoute(this.map, {
                renderOptions: { map: this.map, panel: 'r-result', autoViewport: true },
                //配置跨城公交的交通方式策略为飞机优先
                transitTypePolicy: BMAP_TRANSIT_TYPE_POLICY_AIRPLANE,
                policy: 0,
            });
            //条件查询
            console.log(value, 123);
            this.transits.setPolicy(value);
            var start = new BMap.Point(this.state.startPoint.lng, this.state.startPoint.lat);
            var end = new BMap.Point(this.state.endPoint.lng, this.state.endPoint.lat);
            //根据坐标查询
            this.transits.search(start, end);
            document.getElementById('MapList').style.display = 'block'
        }
    }

    TravelMode = (e) => {
        this.setState({
            title: e.title
        })
        setTimeout(() => {
            this.TravelPlan()
        }, 100)
    }

    TravelPlan = (e) => {
        let condition = e ? e.title : this.state.condition
        if (this.state.start && this.state.end) {
            console.log('两个位置都有');
            if (this.state.title === '驾车') {

                if (condition === '最短距离') {
                    this.drive(BMAP_DRIVING_POLICY_FIRST_HIGHWAYS)
                } else {
                    this.drive(BMAP_DRIVING_POLICY_AVOID_CONGESTION)
                }
            } else if (this.state.title === '公交') {
                if (condition === '最短距离') {
                    this.transit(BMAP_TRANSIT_POLICY_LEAST_TRANSFER)
                } else {
                    this.transit(BMAP_TRANSIT_POLICY_LEAST_TIME)
                }
            } else {
                this.walk()
            }
        }
    }

    close = () => {
        if (this.state.closestatus) {
            console.log(document.getElementById('MapList'));
            document.getElementById('MapList').style.height = '60%'
            this.setState({
                closestatus: false,
                msg: '关闭'
            })
        } else {
            document.getElementById('MapList').style.height = '20%'
            this.setState({
                closestatus: true,
                msg: "展开"
            })
        }
    }
    render() {
        const tabs = [
            { title: '驾车' },
            { title: '公交' },
            { title: '步行' },
        ];
        const tabss = [
            { title: '最少时间' },
            { title: '最短距离' },
        ]
        const style = {
            backgroundImage: 'url(https://zos.alipayobjects.com/rmsportal/DfkJHaJGgMghpXdqNaKF.png)',
            backgroundSize: 'cover',
            height: '22px',
            width: '22px'
        }
        return (
            <div className="MapNav">
                <InputItem placeholder="请输入起始位置" value={this.state.start} onChange={(value) => { this.setState({ start: value }) }} id="start">
                    <div style={style} />
                </InputItem>
                <InputItem placeholder="请输入结束位置" value={this.state.end} onChange={(value) => { this.setState({ end: value }) }} id="end">
                    <div style={style} />
                </InputItem>
                <Tabs tabs={tabs} onTabClick={this.TravelMode}>
                </Tabs>
                <Tabs tabs={tabss}
                    onTabClick={this.TravelPlan}
                    tabBarUnderlineStyle={{ display: "none" }}
                ></Tabs>
                <div id="allmap"></div>
                <div id="MapList">
                    <h3 onClick={this.close}>{this.state.msg}路线详情</h3>
                    <div id="r-result"></div>
                </div>
            </div>
        )
    }
}
